package first.camel.api.router;

import org.apache.activemq.broker.jmx.BrokerViewMBean;
import org.apache.activemq.xbean.XBeanBrokerService;
import org.apache.camel.builder.RouteBuilder                           ;
import org.springframework.beans.factory.InitializingBean               ;
import org.springframework.beans.factory.BeanInitializationException     ;
import org.slf4j.Logger                                                   ;
import org.slf4j.LoggerFactory                                             ;
import org.apache.activemq.broker.BrokerService                              ;

/**
 * User: yuxinlei
 * Date: 4/7/11
 * Time: 8:34 PM
 */
class FirstRouter extends RouteBuilder implements InitializingBean{
    private static final Logger logger = LoggerFactory.getLogger(FirstRouter.class)      ;

    private String sourceUri;
    private String queueName;
    private String brokerURi;
    private static XBeanBrokerService brokerService;


    public void afterPropertiesSet() {
        if (getSourceUri() == null) {
			throw new BeanInitializationException("The source Uri is null! ");
		}

        /**
         *  <broker:broker useJmx="false" persistent="false" brokerName="localhost">
    <broker:transportConnectors>
      <broker:transportConnector name="tcp" uri="tcp://localhost:61616" />
    </broker:transportConnectors>
  </broker:broker>
         */
         if(brokerService!=null){
           createBroker(brokerURi)   ;
         }

		logger.debug("Created endpoint to route from " + getSourceUri() + "to queue '" + getQueueName() + "'" );
    }

    public static void createBroker(final String url){
        BrokerViewMBean brokerViewMBean ;
        brokerService = new XBeanBrokerService()           ;
        brokerService.setBrokerName("localhostBroker");
        brokerService.setUseJmx(true);
        brokerService.setPersistent(false);
        try {
            brokerService.addConnector(url);

             brokerService.start()        ;
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    @Override
    public void configure() {
        from(getSourceUri())
			.convertBodyTo(String.class)
			.to("activemq:queue:" + getQueueName());
    }

    public String getSourceUri() {
        return sourceUri;
    }

    public void setSourceUri(String sourceUri) {
        this.sourceUri = sourceUri;
    }

    public String getQueueName() {
        return queueName;
    }

    public void setQueueName(String queueName) {
        this.queueName = queueName;
    }

    public String getBrokerURi() {
        return brokerURi;
    }

    public void setBrokerURi(String brokerURi) {
        this.brokerURi = brokerURi;
    }
}
